package cn.finedo.util;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ThreadLocalRandom;

public class IdUtil {

    private static final String ALLOWED_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMddHHmmss");

    public static String getId(String prefix, int length) {
        if (length <= 0 || prefix == null) {
            throw new IllegalArgumentException("Invalid length or prefix");
        }

        // 获取当前时间戳并格式化为字符串
        String timestamp = DATE_FORMAT.format(new Date());

        // 预留出时间戳和前缀的长度，计算随机字符串的长度
        int randomStringLength = length - prefix.length() - timestamp.length();
        if (randomStringLength < 0) {
            throw new IllegalArgumentException("Length is too short for the given prefix and timestamp");
        }

        // 生成随机字符串
        StringBuilder randomString = new StringBuilder();
        for (int i = 0; i < randomStringLength; i++) {
            int index = ThreadLocalRandom.current().nextInt(ALLOWED_CHARS.length());
            randomString.append(ALLOWED_CHARS.charAt(index));
        }

        // 拼接前缀、时间戳和随机字符串生成最终ID
        return prefix + timestamp + randomString.toString();
    }

}
